package struts.annotation.util;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import struts.annotation.annotation.RequstMapping;


public class FindRequestMappingAction {
	
	private static Set<Class<?>> clazzSet=new LinkedHashSet<Class<?>>();
	
	public static Class<?> getClassByRequestMapping(String requestMappingPath){
		//加载字节码
		Class<?> targetClass = null;
		for (Class<?> clazz : clazzSet) {
			if(clazz.isAnnotationPresent(RequstMapping.class)){
				try {
					if(clazz.getAnnotation(RequstMapping.class).value().equals(requestMappingPath)){
						targetClass=clazz;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}  
				continue;
			}
		}
		return targetClass;
	}
	 
	public static void findAndAddClassInPackageByFile(String fileName,String suffix){
		List<File> list=new LinkedList<File>();	
		getDir(fileName,suffix,list);
		//循环所有文件。
		for(File file:list){
			File[] files=file.listFiles(new FileFilter() {
				@Override
				public boolean accept(File file) {
					return (file.isFile());
				}
			});
			for (File file2 : files) {
				try {
					String filePath=file2.getAbsolutePath();
					filePath=filePath.substring(0,filePath.length()-6);
					filePath=filePath.replaceAll("\\\\", ".");
					filePath=filePath.substring(filePath.indexOf("WEB-INF.classes")+16);
					clazzSet.add(Thread.currentThread().getContextClassLoader().loadClass(filePath));
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	//加载指定包文件
	private static void getDir(String fileName,String suffix,List<File> list){
		File file=new File(fileName);
		if(!file.isDirectory()){
			return;
		}
		File[] files=file.listFiles(new FileFilter() {
			@Override
			public boolean accept(File file) {
				return (file.isDirectory());
			}
		});
		if(files==null||files.length==0){
			return;
		}
		for (File file2 : files) {
			list.add(file2);
			if(file2.getName().equals(suffix)){
				list.remove(list.size()-1);
				list.add(0, file2);
				continue;
			}
			getDir(fileName+"\\"+file2.getName(),suffix,list);
			list.remove(list.size()-1);
		}
	}
	 
}
